using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Identity;
using UserManagementService.Users;
using UserManagementService.DTOs;
using UserManagementService.Permissions;

namespace UserManagementService.Users;

/// <summary>
/// 扩展用户管理控制器
/// </summary>
[ApiController]
[Route("api/users")]
[Authorize]
public class ExtendedUserController : AbpControllerBase
{
    private readonly IExtendedUserAppService _userAppService;
    private readonly ILogger<ExtendedUserController> _logger;

    public ExtendedUserController(
        IExtendedUserAppService userAppService,
        ILogger<ExtendedUserController> logger)
    {
        _userAppService = userAppService;
        _logger = logger;
    }

    /// <summary>
    /// 获取用户列表
    /// </summary>
    [HttpGet]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<PagedResultDto<IdentityUserDto>> GetListAsync(PagedAndSortedResultRequestDto input)
    {
        try
        {
            return await _userAppService.GetListAsync(input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户列表失败");
            throw new UserFriendlyException("获取用户列表失败", ex.Message);
        }
    }

    /// <summary>
    /// 根据ID获取用户
    /// </summary>
    [HttpGet("{id}")]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<IdentityUserDto> GetAsync(Guid id)
    {
        try
        {
            return await _userAppService.GetAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户详情失败: {UserId}", id);
            throw new UserFriendlyException("获取用户详情失败", ex.Message);
        }
    }

    /// <summary>
    /// 根据用户名获取用户
    /// </summary>
    [HttpGet("by-username/{username}")]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<IdentityUserDto> GetByUserNameAsync(string username)
    {
        try
        {
            return await _userAppService.GetByUserNameAsync(username);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据用户名获取用户失败: {UserName}", username);
            throw new UserFriendlyException("获取用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 根据邮箱获取用户
    /// </summary>
    [HttpGet("by-email/{email}")]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<IdentityUserDto> GetByEmailAsync(string email)
    {
        try
        {
            return await _userAppService.GetByEmailAsync(email);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据邮箱获取用户失败: {Email}", email);
            throw new UserFriendlyException("获取用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 根据手机号获取用户
    /// </summary>
    [HttpGet("by-phone/{phoneNumber}")]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<IdentityUserDto> GetByPhoneNumberAsync(string phoneNumber)
    {
        try
        {
            return await _userAppService.GetByPhoneNumberAsync(phoneNumber);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据手机号获取用户失败: {PhoneNumber}", phoneNumber);
            throw new UserFriendlyException("获取用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    [HttpPost]
    [Authorize(UserManagementPermissions.UserPermissions.Create)]
    public async Task<IdentityUserDto> CreateAsync(CreateUserDto input)
    {
        try
        {
            _logger.LogInformation("创建用户: {UserName}", input.UserName);
            return await _userAppService.CreateAsync(input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建用户失败: {UserName}", input.UserName);
            throw new UserFriendlyException("创建用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    [HttpPut("{id}")]
    [Authorize(UserManagementPermissions.UserPermissions.Edit)]
    public async Task<IdentityUserDto> UpdateAsync(Guid id, UpdateUserDto input)
    {
        try
        {
            _logger.LogInformation("更新用户: {UserId}", id);
            return await _userAppService.UpdateAsync(id, input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新用户失败: {UserId}", id);
            throw new UserFriendlyException("更新用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    [HttpDelete("{id}")]
    [Authorize(UserManagementPermissions.UserPermissions.Delete)]
    public async Task DeleteAsync(Guid id)
    {
        try
        {
            _logger.LogInformation("删除用户: {UserId}", id);
            await _userAppService.DeleteAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除用户失败: {UserId}", id);
            throw new UserFriendlyException("删除用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 获取用户统计信息
    /// </summary>
    [HttpGet("statistics")]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<UserStatisticsDto> GetUserStatisticsAsync()
    {
        try
        {
            return await _userAppService.GetUserStatisticsAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户统计信息失败");
            throw new UserFriendlyException("获取统计信息失败", ex.Message);
        }
    }

    /// <summary>
    /// 批量更新用户状态
    /// </summary>
    [HttpPut("batch-update-status")]
    [Authorize(UserManagementPermissions.UserPermissions.Manage)]
    public async Task BatchUpdateUserStatusAsync(BatchUpdateUserStatusDto input)
    {
        try
        {
            _logger.LogInformation("批量更新用户状态: {Count} 个用户, 状态: {Status}",
                input.UserIds.Count, input.Status);
            await _userAppService.BatchUpdateUserStatusAsync(input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量更新用户状态失败");
            throw new UserFriendlyException("批量更新用户状态失败", ex.Message);
        }
    }

    /// <summary>
    /// 搜索用户
    /// </summary>
    [HttpPost("search")]
    [Authorize(UserManagementPermissions.UserPermissions.Default)]
    public async Task<PagedResultDto<IdentityUserDto>> SearchUsersAsync(SearchUsersDto input)
    {
        try
        {
            return await _userAppService.SearchUsersAsync(input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "搜索用户失败: {Keyword}", input.Keyword);
            throw new UserFriendlyException("搜索用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 获取用户权限
    /// </summary>
    [HttpGet("{id}/permissions")]
    [Authorize(UserManagementPermissions.UserPermissions.ViewPermissions)]
    public async Task<List<string>> GetUserPermissionsAsync(Guid id)
    {
        try
        {
            return await _userAppService.GetUserPermissionsAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户权限失败: {UserId}", id);
            throw new UserFriendlyException("获取用户权限失败", ex.Message);
        }
    }

    /// <summary>
    /// 获取用户角色
    /// </summary>
    [HttpGet("{id}/roles")]
    [Authorize(UserManagementPermissions.UserPermissions.ViewRoles)]
    public async Task<List<string>> GetUserRolesAsync(Guid id)
    {
        try
        {
            return await _userAppService.GetUserRolesAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户角色失败: {UserId}", id);
            throw new UserFriendlyException("获取用户角色失败", ex.Message);
        }
    }

    /// <summary>
    /// 获取用户组织
    /// </summary>
    [HttpGet("{id}/organizations")]
    [Authorize(UserManagementPermissions.UserPermissions.ViewOrganizations)]
    public async Task<List<OrganizationDto>> GetUserOrganizationsAsync(Guid id)
    {
        try
        {
            return await _userAppService.GetUserOrganizationsAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户组织失败: {UserId}", id);
            throw new UserFriendlyException("获取用户组织失败", ex.Message);
        }
    }

    /// <summary>
    /// 解锁用户
    /// </summary>
    [HttpPost("{id}/unlock")]
    [Authorize(UserManagementPermissions.UserPermissions.Unlock)]
    public async Task UnlockUserAsync(Guid id)
    {
        try
        {
            _logger.LogInformation("解锁用户: {UserId}", id);
            await _userAppService.UnlockUserAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "解锁用户失败: {UserId}", id);
            throw new UserFriendlyException("解锁用户失败", ex.Message);
        }
    }

    /// <summary>
    /// 强制用户修改密码
    /// </summary>
    [HttpPost("{id}/force-password-change")]
    [Authorize(UserManagementPermissions.UserPermissions.Manage)]
    public async Task ForcePasswordChangeAsync(Guid id, [FromBody] bool forceChange)
    {
        try
        {
            _logger.LogInformation("强制用户修改密码: {UserId}, 强制: {ForceChange}", id, forceChange);
            await _userAppService.ForcePasswordChangeAsync(id, forceChange);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "强制用户修改密码失败: {UserId}", id);
            throw new UserFriendlyException("操作失败", ex.Message);
        }
    }

    /// <summary>
    /// 重置用户密码
    /// </summary>
    [HttpPost("{id}/reset-password")]
    [Authorize(UserManagementPermissions.UserPermissions.Manage)]
    public async Task<string> ResetPasswordAsync(Guid id)
    {
        try
        {
            _logger.LogInformation("重置用户密码: {UserId}", id);
            return await _userAppService.ResetPasswordAsync(id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "重置用户密码失败: {UserId}", id);
            throw new UserFriendlyException("重置密码失败", ex.Message);
        }
    }

    /// <summary>
    /// 发送密码重置邮件
    /// </summary>
    [HttpPost("send-password-reset-email")]
    [AllowAnonymous]
    public async Task SendPasswordResetEmailAsync([FromBody] string email)
    {
        try
        {
            _logger.LogInformation("发送密码重置邮件: {Email}", email);
            await _userAppService.SendPasswordResetEmailAsync(email);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送密码重置邮件失败: {Email}", email);
            throw new UserFriendlyException("发送邮件失败", ex.Message);
        }
    }

    /// <summary>
    /// 导出用户数据
    /// </summary>
    [HttpPost("export")]
    [Authorize(UserManagementPermissions.UserPermissions.Export)]
    public async Task<FileDownloadResultDto> ExportUsersAsync(ExportUsersDto input)
    {
        try
        {
            _logger.LogInformation("导出用户数据");
            return await _userAppService.ExportUsersAsync(input);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导出用户数据失败");
            throw new UserFriendlyException("导出失败", ex.Message);
        }
    }
}